package com.wcbdota.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.wcbdota.base.C;

public class AsyncAppLoader {

	private static String TAG = AsyncAppLoader.class.getSimpleName();
	private static String upgradeUrl = C.res.base + C.res.upgradedir + "/" + C.config.updatefilename;

	public AsyncAppLoader() {	}

	public boolean loadApp(final AppLoaderCallback apploadercallback) {
		
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				apploadercallback.AppLoaded(message.what);
			}
		};
		
		new Thread() {
			@Override
			public void run() {
				loadAppFromUrl();
				Message message = handler.obtainMessage(0);
				try {
					Thread.sleep(new Random().nextInt(3000));
				}
				catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
		
		return false;
	}

	public static boolean loadAppFromUrl() {
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(upgradeUrl);
		HttpResponse response;
		try {
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			long length = entity.getContentLength();
			InputStream is = entity.getContent();
			FileOutputStream fileOutputStream = null;
			if (is != null) {
				File f = new File(C.dir.loadapp);
				if (!f.exists()) {
					f.mkdirs();
				}
				fileOutputStream = new FileOutputStream(new File(C.dir.loadapp, C.config.updatefilename));

				byte[] buf = new byte[1024];
				int ch = -1;
				int count = 0;
				while ((ch = is.read(buf)) != -1) {
					fileOutputStream.write(buf, 0, ch);
					count += ch;
					Log.d(TAG, String.valueOf(count));
					if (length > 0) {
					}
				}
			}
			fileOutputStream.flush();
			if (fileOutputStream != null) {
				fileOutputStream.close();
			}

		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
		return false;
	}

	public interface AppLoaderCallback {
		public void AppLoaded(int result);
	}
}
